// 消息处理核心逻辑
import { Ref } from 'vue';
import type { Message } from './chat-types';
import websocketService from '../services/websocket';
import {
  checkMessageExistsByMessageId,
  checkMessageDuplicate,
  processMessageContent,
  checkIsFromCurrentUser,
  checkIsMentioned,
  triggerNewMessageNotification
} from './chat-message-handler';

/**
 * 处理接收到的消息
 */
export async function handleIncomingMessage(
  message: any,
  messages: Ref<Message[]>,
  currentUserId: Ref<string | null>,
  currentTargetId: Ref<string | null>,
  targetType: Ref<'User' | 'Group'>,
  saveMessagesToStorage: () => Promise<void>,
  getDeletedMessageIds?: () => Promise<Set<string>>
): Promise<void> {
  // 只在开发环境且需要调试时输出详细日志，减少日志噪音
  // 注释掉频繁的日志输出，只在真正需要调试时启用
  // if (import.meta.env.DEV) {
  //   console.log('🟢 === ChatStore 收到消息 ===');
  //   console.log('🟢 ChatStore 消息对象:', message);
  //   console.log('🟢 ChatStore 消息类型:', typeof message);
  //   console.log('🟢 ChatStore 消息是否有 message_id:', message?.message_id);
  //   console.log('🟢 ChatStore 消息键:', message && typeof message === 'object' ? Object.keys(message) : 'null');
  //   console.log('🟢 ChatStore 原始消息字段检查:', {
  //     has_from_user_id: 'from_user_id' in (message || {}),
  //     has_to_user_id: 'to_user_id' in (message || {}),
  //     from_user_id: message?.from_user_id,
  //     to_user_id: message?.to_user_id,
  //     from_id: message?.from_id,
  //     to_id: message?.to_id,
  //     message_id: message?.message_id,
  //     chat_type: message?.chat_type,
  //   });
  // }

  // 检查是否是好友请求通知
  if (message && message.message) {
    try {
      let messageContent = message.message;
      if (typeof messageContent === 'string') {
        try {
          const parsed = JSON.parse(messageContent);
          if (parsed && parsed.type === 'friendship_request') {
            console.log('收到好友请求通知（WebSocket）:', parsed);
            websocketService.trigger('friendship_request', parsed);
            return;
          }
        } catch (e) {
          // 不是 JSON，继续处理为普通消息
        }
      }
    } catch (e) {
      // 解析失败，继续处理
    }
  }

  // 如果消息本身就是一个好友请求通知对象
  if (message && typeof message === 'object' && message.type === 'friendship_request') {
    console.log('收到好友请求通知（直接格式）:', message);
    websocketService.trigger('friendship_request', message);
    return;
  }

  // 检查是否是通话邀请消息
  // 重要：通话邀请消息（message_content_type === 4 或 type === "call_invite"）不应该显示在聊天界面
  // 无论是否过期、是否处理成功，都不应该添加到消息列表
  
  // 检查消息本身是否是通话邀请格式（直接格式：{"type":"call_invite",...}）
  const isDirectCallInvite = message && typeof message === 'object' && message.type === 'call_invite';
  
  // 检查消息内容类型是否是通话邀请（标准格式：message_content_type === 4）
  const messageContentType = (message as any)?.message_content_type;
  const isCallInviteByContentType = messageContentType === 4;
  
  // 检查消息内容是否是通话邀请格式（消息内容为 JSON，包含 type: "call_invite"）
  let isCallInviteByMessageContent = false;
  let inviteDataFromContent: any = null;
  if (message && message.message && typeof message.message === 'string') {
    try {
      const parsed = JSON.parse(message.message);
      if (parsed && parsed.type === 'call_invite') {
        isCallInviteByMessageContent = true;
        inviteDataFromContent = parsed;
      }
    } catch (e) {
      // 不是 JSON，忽略
    }
  }

  // 检查是否是通话取消消息（message_content_type === 5 或 type === "call_cancel"）
  const isCallCancelByContentType = messageContentType === 5;
  let isCallCancelByMessageContent = false;
  if (message && message.message && typeof message.message === 'string') {
    try {
      const parsed = JSON.parse(message.message);
      if (parsed && parsed.type === 'call_cancel') {
        isCallCancelByMessageContent = true;
      }
    } catch (e) {
      // 不是 JSON，忽略
    }
  }
  
  // 处理通话取消消息
  if (isCallCancelByContentType || isCallCancelByMessageContent) {
    try {
      const fromUserId = message.from_user_id || message.from_id;
      console.log('📞 收到通话取消消息:', {
        fromUserId,
        messageId: message.message_id,
      });
      
      // 触发通话取消事件，通知通话组件结束通话
      websocketService.trigger('call_cancel', {
        fromUserId: fromUserId,
        messageId: message.message_id,
      });
      
      // 通话取消消息不应该添加到消息列表
      return;
    } catch (e) {
      console.error('处理通话取消消息失败:', e);
      // 即使处理失败，也不应该添加到消息列表
      return;
    }
  }
  
  // 如果是通话邀请消息（任意一种格式），进行处理
  if (isDirectCallInvite || isCallInviteByContentType || isCallInviteByMessageContent) {
    // 无论处理成功与否，通话邀请消息都不应该添加到消息列表
    // 这是实时消息，不应该作为普通文本消息显示
    try {
      // 统一解析通话邀请数据
      let inviteData: any = {};
      let timeout = 60; // 默认60秒超时
      
      if (isDirectCallInvite) {
        // 消息本身就是通话邀请格式
        inviteData = message;
        timeout = message.timeout || 60;
      } else if (inviteDataFromContent) {
        // 从消息内容解析
        inviteData = inviteDataFromContent;
        timeout = inviteData.timeout || 60;
      } else {
        // 尝试从 message 或 message_body 字段解析
        const messageContent = message.message || message.message_body;
        if (messageContent && typeof messageContent === 'string') {
          try {
            inviteData = JSON.parse(messageContent);
            timeout = inviteData.timeout || 60;
          } catch (e) {
            // 如果不是 JSON，使用默认值
            inviteData = {
              isVoiceOnly: messageContent === 'voice' || messageContent.includes('voice'),
            };
          }
        }
      }
      
      // 兼容性处理：支持 isVoiceOnly 和 is_voice_only 两种字段名
      if (inviteData.isVoiceOnly === undefined && inviteData.is_voice_only !== undefined) {
        inviteData.isVoiceOnly = inviteData.is_voice_only;
      }
      
      // 检查是否是当前用户发送的邀请（自己发起的呼叫不应该显示邀请弹窗）
      const fromUserId = message.from_user_id || message.from_id || inviteData.fromUserId;
      const { checkIsFromCurrentUser } = await import('./chat-message-handler');
      const isFromCurrentUser = await checkIsFromCurrentUser(fromUserId, currentUserId.value);
      
      if (isFromCurrentUser) {
        // 自己发送的邀请，静默处理，不输出日志（减少日志噪音）
        return; // 自己发送的邀请，不显示弹窗，也不添加到消息列表
      }
      
      // 只有非自己发送的通话邀请才输出日志
      console.log('📞 收到通话邀请消息（开始处理）:', {
        format: isDirectCallInvite ? 'direct' : (isCallInviteByContentType ? 'content_type' : 'message_content'),
        fromUserId,
        messageId: message.message_id,
        messageTimestamp: message.timestamp || message.timestamp_ms || message.created_at || inviteData.timestamp,
        timeout,
      });
      
      // 检查消息时间戳 + 超时时间，判断通话邀请是否已过期
      // 参考主流IM方案：通话邀请是实时消息，如果消息时间 + 超时时间 < 当前时间，说明已过期
      const messageTimestamp = message.timestamp || message.timestamp_ms || message.created_at || inviteData.timestamp;
      if (messageTimestamp) {
        const messageTime = typeof messageTimestamp === 'number' 
          ? (messageTimestamp > 1000000000000 ? messageTimestamp : messageTimestamp * 1000) // 处理秒级和毫秒级时间戳
          : new Date(messageTimestamp).getTime();
        const now = Date.now();
        const expireTime = messageTime + (timeout * 1000); // 消息时间 + 超时时间（毫秒）
        const timeDiff = now - messageTime; // 消息发送时间距离现在的时间差（毫秒）
        
        // 额外检查：如果时间戳是未来的时间（可能是系统时间错误），也忽略
        if (messageTime > now + 60000) { // 如果时间戳比当前时间晚1分钟以上，可能是系统时间错误
          console.log('通话邀请消息时间戳异常（未来时间），忽略（不显示弹窗，也不添加到消息列表）:', {
            messageTime: new Date(messageTime).toISOString(),
            now: new Date(now).toISOString(),
            timeDiff: `${Math.floor((messageTime - now) / 1000)}秒`
          });
          return;
        }
        
        // 重要：先检查是否已过期（当前时间 > 消息时间 + 超时时间）
        // 这是最严格的判断：如果消息已经过期，无论是实时推送还是离线加载，都不应该显示弹窗
        if (now > expireTime) {
          console.log('这是已过期的通话邀请消息，忽略（不显示弹窗，也不添加到消息列表）:', {
            messageTime: new Date(messageTime).toISOString(),
            expireTime: new Date(expireTime).toISOString(),
            now: new Date(now).toISOString(),
            timeout: `${timeout}秒`,
            expiredBy: `${Math.floor((now - expireTime) / 1000)}秒`,
            timeDiff: `${Math.floor(timeDiff / 1000)}秒`
          });
          return; // 已过期的邀请，不显示弹窗，也不添加到消息列表
        }
        
        // 重要：如果消息是离线消息（从数据库加载的），不应该显示弹窗
        // 判断标准：如果消息发送时间距离现在超过10秒，认为是离线消息
        // 因为实时推送的消息通常会在几秒内到达，超过10秒的消息很可能是从数据库加载的离线消息
        // 这样可以避免用户上线后，加载离线消息时弹出过期的通话邀请
        // 使用10秒而不是超时时间的一半，因为即使消息未过期，如果已经超过10秒，用户很可能已经错过了
        const offlineThreshold = 10 * 1000; // 10秒（毫秒）- 更严格的阈值
        if (timeDiff > offlineThreshold) {
          console.log('🚫 这是离线通话邀请消息（从数据库加载），不显示弹窗（只存储，不推送）:', {
            messageTime: new Date(messageTime).toISOString(),
            now: new Date(now).toISOString(),
            timeDiff: `${Math.floor(timeDiff / 1000)}秒`,
            timeout: `${timeout}秒`,
            offlineThreshold: `${Math.floor(offlineThreshold / 1000)}秒`,
            messageId: message.message_id,
            fromUserId: fromUserId,
            reason: '离线消息，用户不在线时发送，超过10秒后无意义'
          });
          return; // 离线消息，不显示弹窗，也不添加到消息列表
        }
      } else {
        // 如果没有时间戳，检查是否是最近的消息（可能是实时消息）
        // 但为了安全，如果没有时间戳且消息内容中没有timestamp，也忽略（可能是历史消息）
        if (!inviteData.timestamp) {
          console.log('通话邀请消息没有时间戳，可能是历史消息，忽略（不显示弹窗，也不添加到消息列表）');
          return;
        }
      }
      
      console.log('✅ 显示通话邀请弹窗（实时推送，通过所有检查）:', {
        fromUserId,
        messageId: message.message_id,
        messageTime: messageTimestamp ? new Date(typeof messageTimestamp === 'number' 
          ? (messageTimestamp > 1000000000000 ? messageTimestamp : messageTimestamp * 1000)
          : new Date(messageTimestamp).getTime()).toISOString() : 'N/A',
        timeDiff: messageTimestamp ? `${Math.floor((Date.now() - (typeof messageTimestamp === 'number' 
          ? (messageTimestamp > 1000000000000 ? messageTimestamp : messageTimestamp * 1000)
          : new Date(messageTimestamp).getTime())) / 1000)}秒` : 'N/A',
        timeout: `${timeout}秒`,
      });
      websocketService.trigger('call_invite', {
        fromUserId: fromUserId,
        fromUserName: '', // 需要从用户列表获取
        // 兼容性处理：支持 isVoiceOnly 和 is_voice_only，默认为 true（语音通话）
        isVoiceOnly: inviteData.isVoiceOnly !== undefined 
          ? inviteData.isVoiceOnly 
          : (inviteData.is_voice_only !== undefined ? inviteData.is_voice_only : true),
        messageId: message.message_id,
        timeout: timeout, // 使用解析出的超时时间
        timestamp: messageTimestamp, // 传递时间戳，用于事件监听器检查
      });
      // 重要：无论是否显示弹窗，通话邀请消息都不应该添加到消息列表
      return; // 不将通话邀请消息添加到消息列表
    } catch (e) {
      console.error('处理通话邀请消息失败:', e);
      // 重要：即使处理失败，通话邀请消息也不应该添加到消息列表
      // 这是实时消息，不应该作为普通文本消息显示在聊天界面
      console.log('通话邀请消息处理失败，但不会添加到消息列表（这是实时消息，不应该显示为文本）');
      return; // 不继续处理为普通消息
    }
  }

  // 确保消息格式正确
  if (!message) {
    console.warn('⚠️ 收到空消息，跳过处理');
    return;
  }
  
  // 如果消息是字符串，尝试解析
  if (typeof message === 'string') {
    console.log('🟢 消息是字符串，尝试解析 JSON');
    try {
      message = JSON.parse(message);
      console.log('🟢 解析后的消息:', message);
    } catch (e) {
      console.error('🔴 解析消息 JSON 失败:', e, '原始消息:', message);
      return;
    }
  }
  
  if (message && message.message_id) {
    const incomingMessageId = String(message.message_id);
    
    // 检查消息是否在已删除列表中
    if (getDeletedMessageIds) {
      const deletedIds = await getDeletedMessageIds();
      if (deletedIds.has(incomingMessageId)) {
        console.log('⚠️ 消息已被删除，跳过同步:', {
          message_id: incomingMessageId,
          from_user_id: message.from_user_id,
          to_user_id: message.to_user_id,
        });
        return;
      }
    }
    
    const incomingTimestamp = message.timestamp_ms || message.timestamp || Date.now();
    const incomingContent = String(message.message || '');
    const incomingFileUrl = message.file_url || '';
    const incomingChatType = message.chat_type;
    
    // 尝试多种可能的字段名（兼容不同的消息格式）
    const incomingFromId = String(
      message.from_user_id || 
      message.from_id || 
      (message as any).from_user || 
      ''
    ).trim();
    const incomingToId = String(
      message.to_user_id || 
      message.to_id || 
      (message as any).to_user || 
      ''
    ).trim();
    
    // 如果字段为空，记录警告并尝试继续处理（可能可以从其他字段推断）
    if (!incomingFromId || !incomingToId) {
      console.error('🔴 消息缺少必要的用户ID字段:', {
        message_id: incomingMessageId,
        message_keys: Object.keys(message || {}),
        from_user_id: message.from_user_id,
        to_user_id: message.to_user_id,
        from_id: (message as any).from_id,
        to_id: (message as any).to_id,
        full_message: JSON.stringify(message, null, 2)
      });
      
      // 如果消息缺少关键字段，可能是格式错误，但仍然尝试处理
      // 注意：这可能会导致消息无法正确显示，但至少不会丢失消息
      console.warn('⚠️ 消息格式可能不正确，但将继续处理（可能导致显示问题）');
    }

    // 检查消息是否已存在（基于 message_id）
    if (checkMessageExistsByMessageId(messages.value, incomingMessageId)) {
      console.log('⚠️ 消息已存在（基于 message_id），跳过重复添加:', {
        message_id: incomingMessageId,
        from_user_id: incomingFromId,
        to_user_id: incomingToId,
        chat_type: incomingChatType,
        content: incomingContent.substring(0, 50)
      });
      return;
    }

    // 判断是否是当前用户发送的消息
    const isFromCurrentUser = await checkIsFromCurrentUser(incomingFromId, currentUserId.value);
    
    console.log('🔍 消息处理详情:', {
      message_id: incomingMessageId,
      from_user_id: incomingFromId,
      to_user_id: incomingToId,
      current_user_id: currentUserId.value,
      isFromCurrentUser,
      chat_type: incomingChatType,
      content_preview: incomingContent.substring(0, 50),
      is_group_message: incomingChatType === 2,
      full_message: JSON.stringify(message, null, 2)
    });

    // 检查是否有重复消息（基于内容和时间戳）
    const duplicateCheck = checkMessageDuplicate(
      messages.value,
      message,
      incomingMessageId,
      incomingTimestamp,
      incomingContent,
      incomingFileUrl,
      incomingChatType,
      incomingFromId,
      incomingToId,
      isFromCurrentUser
    );

    if (duplicateCheck.isDuplicate && duplicateCheck.duplicateIndex !== undefined) {
      // 如果是自己发送的消息，用后端返回的真实消息替换临时消息
      if (isFromCurrentUser) {
        console.log('🔄 找到重复的临时消息，用后端消息替换:', {
          index: duplicateCheck.duplicateIndex,
          oldId: messages.value[duplicateCheck.duplicateIndex].message_id,
          newId: incomingMessageId,
          content: incomingContent.substring(0, 30) || incomingFileUrl
        });
        const duplicateMsg = messages.value[duplicateCheck.duplicateIndex];
        messages.value[duplicateCheck.duplicateIndex] = {
          ...duplicateMsg,
          message_id: incomingMessageId,
          file_url: incomingFileUrl || duplicateMsg.file_url,
          file_name: message.file_name || duplicateMsg.file_name,
          file_type: message.file_type || duplicateMsg.file_type,
          message_content_type: (message as any).message_content_type || duplicateMsg.message_content_type,
          chat_type: (message as any).chat_type !== undefined ? (message as any).chat_type : duplicateMsg.chat_type,
          timestamp_ms: incomingTimestamp,
          timestamp: incomingTimestamp,
        };
        await saveMessagesToStorage();
        return;
      } else {
        console.log('⚠️ 消息已存在（基于内容和时间戳），跳过重复添加:', {
          message_id: incomingMessageId,
          from_user_id: message.from_user_id,
          to_user_id: message.to_user_id,
          chat_type: message.chat_type,
          content: incomingContent.substring(0, 50)
        });
        return;
      }
    }

    // 处理消息内容
    const { messageContent, fileUrl, fileName, fileType } = processMessageContent(message);

    // 判断是否是接收的消息
    // 重要：对于单聊消息，需要同时检查 from_user_id 和 to_user_id
    // 单聊消息：from_user_id 是发送方，to_user_id 是接收方
    // 如果 from_user_id 不是当前用户，且 to_user_id 是当前用户，说明是接收的消息
    const toUserIdStr = String(message.to_user_id || message.to_id || '').trim();
    const currentUserIdStr = String(currentUserId.value || '').trim();
    const currentOpenId = localStorage.getItem('openId') || '';
    
    // 检查 to_user_id 是否是当前用户
    let isToCurrentUser = false;
    if (toUserIdStr) {
      isToCurrentUser = toUserIdStr === currentUserIdStr || 
                       toUserIdStr === currentOpenId;
      
      // 也检查其他可能的ID格式
      if (!isToCurrentUser) {
        try {
          const userStr = localStorage.getItem('user') || '{}';
          const user = JSON.parse(userStr);
          isToCurrentUser = toUserIdStr === (user.open_id || '') || 
                           toUserIdStr === (user.name || '');
        } catch (e) {
          // 解析失败，忽略
        }
      }
    }
    
    // 对于单聊消息（chat_type === 1），如果 to_user_id 是当前用户，说明是接收的消息
    // 对于群聊消息（chat_type === 2），如果 from_user_id 不是当前用户，说明是接收的消息
    let isReceived = false;
    if (incomingChatType === 1) {
      // 单聊：to_user_id 是当前用户，且 from_user_id 不是当前用户
      isReceived = isToCurrentUser && !isFromCurrentUser;
    } else if (incomingChatType === 2) {
      // 群聊：from_user_id 不是当前用户
      isReceived = !isFromCurrentUser;
    } else {
      // 未知类型，使用默认逻辑
      isReceived = !isFromCurrentUser;
    }
    
    // 添加调试日志
    if (import.meta.env.DEV && incomingChatType === 1) {
      console.log('💬 单聊消息 isReceived 判断:', {
        message_id: incomingMessageId,
        from_user_id: incomingFromId,
        to_user_id: incomingToId,
        current_user_id: currentUserIdStr,
        current_open_id: currentOpenId,
        isFromCurrentUser,
        isToCurrentUser,
        isReceived,
        chat_type: incomingChatType,
      });
    }

    // 检查是否是自己给自己发的消息
    if (isFromCurrentUser) {
      const toUserIdStr = String(message.to_user_id || '');
      const currentUserIdStr = String(currentUserId.value || '');
      
      if (toUserIdStr === currentUserIdStr || 
          toUserIdStr === (localStorage.getItem('openId') || '') ||
          (() => {
            try {
              const userStr = localStorage.getItem('user') || '{}';
              const user = JSON.parse(userStr);
              return toUserIdStr === (user.open_id || '') || toUserIdStr === (user.name || '');
            } catch {
              return false;
            }
          })()) {
        // 自己给自己发的消息，只显示一次（作为发送的消息）
        const hasTempMessage = messages.value.some(msg => 
          !msg.isReceived && 
          String(msg.from_user_id || '') === String(message.from_user_id || '') &&
          String(msg.to_user_id || '') === toUserIdStr &&
          (String(msg.message || '') === String(message.message || '') || 
           (msg.file_url && message.file_url && msg.file_url === message.file_url)) &&
          Math.abs((msg.timestamp_ms || msg.timestamp || 0) - (message.timestamp_ms || message.timestamp || 0)) < 10000
        );
        
        if (hasTempMessage) {
          console.log('⚠️ 检测到自己给自己发的消息，且已有临时消息，跳过重复添加');
          return;
        }
        
        isReceived = false;
      }
    }

    // 推断 chat_type
    let chatType = (message as any).chat_type;
    
    // 如果 chat_type 未设置，尝试多种方式推断
    if (chatType === undefined || chatType === null) {
      const toId = String(message.to_user_id || message.to_id || '').trim();
      
      // 方法1：检查 to_user_id 是否看起来像群组ID（包含 group_ 前缀或特定格式）
      const looksLikeGroupId = toId.startsWith('group_') || 
                               /^[a-z0-9_]+_[a-z0-9]+$/i.test(toId) ||
                               toId.length > 20; // 群组ID通常比较长
      
      if (looksLikeGroupId) {
        console.log('🔍 根据 to_user_id 格式推断为群组消息:', {
          message_id: message.message_id,
          to_user_id: toId,
          reason: 'to_user_id 格式像群组ID',
        });
        chatType = 2;
      } else {
        // 方法2：从群组列表中查找
        try {
          const groupsStr = localStorage.getItem('groups') || '[]';
          const groups = JSON.parse(groupsStr);
          
          const isInGroupList = groups.some((g: any) => {
            const group = g.group || g;
            const groupId = String(group.group_id || '');
            const normalizedGroupId = groupId.replace(/^group_/i, '').toLowerCase();
            const normalizedToId = toId.replace(/^group_/i, '').toLowerCase();
            return normalizedGroupId === normalizedToId || groupId === toId;
          });
          
          if (isInGroupList) {
            chatType = 2;
            console.log('✅ 从群组列表推断为群组消息:', {
              message_id: message.message_id,
              to_user_id: toId,
              inferred_chat_type: chatType,
              groups_count: groups.length,
            });
          } else {
            chatType = 1; // 默认为单聊
            console.log('✅ 推断为单聊消息:', {
              message_id: message.message_id,
              to_user_id: toId,
              inferred_chat_type: chatType,
            });
          }
        } catch (e) {
          console.warn('消息缺少 chat_type 字段，且无法自动推断:', {
            message_id: message.message_id,
            to_user_id: toId,
            from_user_id: incomingFromId,
            error: e,
          });
          // 如果无法推断，根据 to_user_id 格式判断
          chatType = looksLikeGroupId ? 2 : 1;
        }
      }
    } else {
      console.log('✅ 消息已有 chat_type:', {
        message_id: message.message_id,
        to_user_id: message.to_user_id || message.to_id,
        chat_type: chatType,
        is_group_message: chatType === 2,
      });
    }

    const processedMessage: Message = {
      message_id: String(message.message_id || ''),
      from_user_id: String(message.from_user_id || message.from_id || ''),
      to_user_id: String(message.to_user_id || message.to_id || message.group_id || ''),
      message: messageContent,
      timestamp_ms: message.timestamp_ms || message.timestamp || message.message_time || Date.now(),
      timestamp: message.timestamp_ms || message.timestamp || message.message_time || Date.now(),
      isReceived: isReceived,
      file_url: fileUrl,
      file_name: fileName,
      file_type: fileType,
      message_content_type: (message as any).message_content_type,
      chat_type: chatType,
    };
    
    // 添加详细的群组消息日志
    if (chatType === 2) {
      console.log('🔵 群组消息处理完成:', {
        message_id: processedMessage.message_id,
        from_user_id: processedMessage.from_user_id,
        to_user_id: processedMessage.to_user_id,
        isReceived: processedMessage.isReceived,
        chat_type: processedMessage.chat_type,
        message_preview: processedMessage.message?.substring(0, 50),
        has_file: !!processedMessage.file_url,
      });
    }

    // 再次检查是否已存在（防止并发问题）
    const existingByMessageId = messages.value.find(m => {
      const existingId = String(m.message_id);
      const incomingId = String(processedMessage.message_id);
      
      if (existingId === incomingId) {
        return true;
      }
      
      // 检查内容和时间戳
      const existingChatType = m.chat_type;
      const incomingChatType = processedMessage.chat_type;
      
      if (existingChatType !== undefined && incomingChatType !== undefined && existingChatType !== incomingChatType) {
        return false;
      }
      
      // 群组消息检查
      if (incomingChatType === 2 && existingChatType === 2) {
        const existingToId = String(m.to_user_id || '').replace(/^group_/i, '').toLowerCase();
        const incomingToId = String(processedMessage.to_user_id || '').replace(/^group_/i, '').toLowerCase();
        
        if (existingToId === incomingToId) {
          const existingFromId = String(m.from_user_id || '').trim();
          const incomingFromId = String(processedMessage.from_user_id || '').trim();
          const existingContent = String(m.message || '').replace(/\s+/g, '').trim();
          const incomingContent = String(processedMessage.message || '').replace(/\s+/g, '').trim();
          const existingFileUrl = String(m.file_url || '').trim();
          const incomingFileUrl = String(processedMessage.file_url || '').trim();
          const existingTimestamp = m.timestamp_ms || m.timestamp || 0;
          const incomingTimestamp = processedMessage.timestamp_ms || processedMessage.timestamp || 0;
          
          const contentMatch = existingContent === incomingContent;
          const normalizeFileUrl = (url: string) => {
            if (!url) return '';
            const normalized = url.split('?')[0].split('#')[0].toLowerCase();
            const parts = normalized.split('/');
            return parts[parts.length - 1] || normalized;
          };
          const existingFileUrlCore = normalizeFileUrl(existingFileUrl);
          const incomingFileUrlCore = normalizeFileUrl(incomingFileUrl);
          const fileUrlMatch = (!existingFileUrl && !incomingFileUrl) ? true :
                              (existingFileUrl && incomingFileUrl && (
                                existingFileUrl === incomingFileUrl ||
                                (existingFileUrlCore && incomingFileUrlCore && existingFileUrlCore === incomingFileUrlCore) ||
                                existingFileUrl.toLowerCase().includes(incomingFileUrl.toLowerCase()) ||
                                incomingFileUrl.toLowerCase().includes(existingFileUrl.toLowerCase())
                              ));
          
          const isDuplicate = (!existingFileUrl && !incomingFileUrl) ? 
                              contentMatch :
                              (existingFileUrl && incomingFileUrl) ?
                              fileUrlMatch :
                              false;
          
          if (existingFromId === incomingFromId && 
              isDuplicate &&
              (existingTimestamp === incomingTimestamp || Math.abs(existingTimestamp - incomingTimestamp) < 10000)) {
            return true;
          }
        }
      }
      // 单聊消息检查
      else if ((incomingChatType === 1 || incomingChatType === undefined) && 
               (existingChatType === 1 || existingChatType === undefined)) {
        const existingFromId = String(m.from_user_id || '').trim();
        const incomingFromId = String(processedMessage.from_user_id || '').trim();
        const existingToId = String(m.to_user_id || '').trim();
        const incomingToId = String(processedMessage.to_user_id || '').trim();
        
        const fromMatch = existingFromId === incomingFromId;
        const toMatch = existingToId === incomingToId;
        
        if (fromMatch && toMatch) {
          const existingContent = String(m.message || '').replace(/\s+/g, '').trim();
          const incomingContent = String(processedMessage.message || '').replace(/\s+/g, '').trim();
          const existingFileUrl = String(m.file_url || '').trim();
          const incomingFileUrl = String(processedMessage.file_url || '').trim();
          const existingTimestamp = m.timestamp_ms || m.timestamp || 0;
          const incomingTimestamp = processedMessage.timestamp_ms || processedMessage.timestamp || 0;
          
          const contentMatch = existingContent === incomingContent;
          const normalizeFileUrl = (url: string) => {
            if (!url) return '';
            const normalized = url.split('?')[0].split('#')[0].toLowerCase();
            const parts = normalized.split('/');
            return parts[parts.length - 1] || normalized;
          };
          const existingFileUrlCore = normalizeFileUrl(existingFileUrl);
          const incomingFileUrlCore = normalizeFileUrl(incomingFileUrl);
          const fileUrlMatch = (!existingFileUrl && !incomingFileUrl) ? true :
                              (existingFileUrl && incomingFileUrl && (
                                existingFileUrl === incomingFileUrl ||
                                (existingFileUrlCore && incomingFileUrlCore && existingFileUrlCore === incomingFileUrlCore) ||
                                existingFileUrl.toLowerCase().includes(incomingFileUrl.toLowerCase()) ||
                                incomingFileUrl.toLowerCase().includes(existingFileUrl.toLowerCase())
                              ));
          
          const isDuplicate = (!existingFileUrl && !incomingFileUrl) ? 
                              contentMatch :
                              (existingFileUrl && incomingFileUrl) ?
                              fileUrlMatch :
                              false;
          
          if (isDuplicate &&
              (existingTimestamp === incomingTimestamp || Math.abs(existingTimestamp - incomingTimestamp) < 10000)) {
            return true;
          }
        }
      }
      
      return false;
    });

    if (existingByMessageId) {
      console.log('⚠️ 消息已存在（基于 message_id 或内容匹配），跳过重复添加');
      return;
    }

    messages.value.push(processedMessage);
    
    // 计算消息是否会被过滤
    let willBeFiltered = 'N/A';
    if (currentTargetId.value) {
      if (processedMessage.chat_type === 2) {
        if (targetType.value === 'Group') {
          const msgGroupId = String(processedMessage.to_user_id || '').replace(/^group_/i, '').toLowerCase();
          const currentGroupId = String(currentTargetId.value || '').replace(/^group_/i, '').toLowerCase();
          willBeFiltered = msgGroupId === currentGroupId ? 'NO (matches group)' : 'YES (different group)';
        } else {
          willBeFiltered = 'YES (not viewing group)';
        }
      } else {
        willBeFiltered = 'N/A (not group message)';
      }
    } else {
      willBeFiltered = 'N/A (no target selected)';
    }
    
    console.log('✅ 消息已成功添加到列表:', {
      message_id: processedMessage.message_id,
      from_user_id: processedMessage.from_user_id,
      to_user_id: processedMessage.to_user_id,
      isReceived: processedMessage.isReceived,
      chat_type: processedMessage.chat_type,
      is_group_message: processedMessage.chat_type === 2,
      current_target_id: currentTargetId.value,
      target_type: targetType.value,
      total_messages: messages.value.length,
      will_be_filtered: willBeFiltered,
      message_preview: processedMessage.message?.substring(0, 50) || '[文件]',
    });
    
    // 如果是群组消息，添加额外的调试信息
    if (processedMessage.chat_type === 2) {
      console.log('🔵 群组消息已添加到消息列表，详细信息:', {
        message_id: processedMessage.message_id,
        to_user_id: processedMessage.to_user_id,
        current_target_id: currentTargetId.value,
        target_type: targetType.value,
        will_be_visible: willBeFiltered.includes('NO'),
        total_messages: messages.value.length,
        group_messages_count: messages.value.filter(m => m.chat_type === 2).length,
      });
    }

    // 不再自动切换聊天目标，让用户手动选择
    // 这样可以避免收到未读消息时强制打开聊天窗口，影响用户体验
    // 消息已保存到消息列表，用户可以在聊天列表中看到未读消息提示
    if (!currentTargetId.value) {
      console.log('用户未选择聊天目标，消息已保存，等待用户手动选择聊天对象');
    } else {
      // 只检查当前目标是否与消息匹配，用于判断是否显示通知
      // 但不自动切换聊天目标
      const currentTargetIdStr = String(currentTargetId.value || '');
      
      if (processedMessage.chat_type === 2) {
        const msgGroupId = String(processedMessage.to_user_id || '').replace('group_', '');
        const currentGroupId = currentTargetIdStr.replace('group_', '');
        
        // 如果消息不匹配当前打开的聊天，不自动切换，只记录日志
        if (targetType.value !== 'Group' || msgGroupId !== currentGroupId) {
          console.log('收到其他群组的消息，不自动切换聊天窗口:', {
            msgGroupId,
            currentGroupId,
            targetType: targetType.value
          });
        }
      } else {
        const fromUserIdStr = String(processedMessage.from_user_id || '');
        
        // 如果消息不匹配当前打开的聊天，不自动切换，只记录日志
        if (targetType.value !== 'User' || fromUserIdStr !== currentTargetIdStr) {
          console.log('收到其他用户的消息，不自动切换聊天窗口:', {
            fromUserId: fromUserIdStr,
            currentTargetId: currentTargetIdStr,
            targetType: targetType.value
          });
        }
      }
    }

    // 保存到存储
    await saveMessagesToStorage();

    // 检查是否被@提及
    let isMentioned = false;
    if (isReceived && processedMessage.chat_type === 2 && processedMessage.message) {
      isMentioned = await checkIsMentioned(processedMessage, isReceived);
    }

    // 触发新消息通知（只对接收的消息且不是自己发送的消息）
    if (isReceived && processedMessage.isReceived && !isFromCurrentUser) {
      const isCurrentChat = (() => {
        if (!currentTargetId.value) return false;
        
        if (processedMessage.chat_type === 2) {
          const msgGroupId = String(processedMessage.to_user_id || '').replace('group_', '');
          const currentGroupId = String(currentTargetId.value || '').replace('group_', '');
          return msgGroupId === currentGroupId;
        }
        
        // 单聊消息：需要更精确的匹配
        // 对于单聊，currentTargetId 应该是好友的ID（from_user_id）
        const msgFromId = String(processedMessage.from_user_id || '').trim();
        const currentTargetIdStr = String(currentTargetId.value || '').trim();
        
        // 直接匹配
        if (msgFromId === currentTargetIdStr) {
          return true;
        }
        
        // 获取目标用户的所有可能ID（用于匹配）
        const getTargetUserIds = (targetId: string): Set<string> => {
          const ids = new Set<string>([targetId]);
          try {
            const friendsStr = localStorage.getItem('friends') || '[]';
            const friends = JSON.parse(friendsStr);
            const friend = friends.find((f: any) => {
              const friendData = f.user || f;
              const friendId = friendData.open_id || friendData.name || f.to_id || '';
              return String(friendId).trim() === targetId;
            });
            
            if (friend) {
              const friendData = friend.user || friend;
              if (friendData.open_id) ids.add(String(friendData.open_id).trim());
              if (friendData.name) ids.add(String(friendData.name).trim());
              if (friend.to_id) ids.add(String(friend.to_id).trim());
            }
          } catch (e) {
            // 解析失败，忽略
          }
          return ids;
        };
        
        // 获取消息发送方的所有可能ID
        const getMessageSenderIds = (fromId: string): Set<string> => {
          const ids = new Set<string>([fromId]);
          try {
            const friendsStr = localStorage.getItem('friends') || '[]';
            const friends = JSON.parse(friendsStr);
            const friend = friends.find((f: any) => {
              const friendData = f.user || f;
              const friendId = friendData.open_id || friendData.name || f.to_id || '';
              return String(friendId).trim() === fromId;
            });
            
            if (friend) {
              const friendData = friend.user || friend;
              if (friendData.open_id) ids.add(String(friendData.open_id).trim());
              if (friendData.name) ids.add(String(friendData.name).trim());
              if (friend.to_id) ids.add(String(friend.to_id).trim());
            }
          } catch (e) {
            // 解析失败，忽略
          }
          return ids;
        };
        
        // 获取目标用户的所有可能ID
        const targetUserIds = getTargetUserIds(currentTargetIdStr);
        // 获取消息发送方的所有可能ID
        const senderIds = getMessageSenderIds(msgFromId);
        
        // 检查是否有交集（如果有任何ID匹配，说明是同一个用户）
        for (const targetId of targetUserIds) {
          if (senderIds.has(targetId)) {
            return true;
          }
        }
        
        return false;
      })();

      if (!isCurrentChat || isMentioned) {
        await triggerNewMessageNotification(processedMessage, isMentioned, isCurrentChat);
      }
    }
  } else {
    console.warn('⚠️ 消息格式不正确，缺少 message_id 字段:', message);
    // 尝试处理没有 message_id 的消息
    if (message && (message.message || message.file_url)) {
      // 判断是否是当前用户发送的消息
      const tempFromId = String(message.from_user_id || message.from_id || '').trim();
      const tempToId = String(message.to_user_id || message.to_id || '').trim();
      const tempCurrentUserId = String(currentUserId.value || '').trim();
      const tempCurrentOpenId = localStorage.getItem('openId') || '';
      
      // 检查是否是当前用户发送的消息
      let tempIsFromCurrentUser = false;
      if (tempFromId) {
        tempIsFromCurrentUser = tempFromId === tempCurrentUserId || tempFromId === tempCurrentOpenId;
        if (!tempIsFromCurrentUser) {
          try {
            const userStr = localStorage.getItem('user') || '{}';
            const user = JSON.parse(userStr);
            tempIsFromCurrentUser = tempFromId === (user.open_id || '') || 
                                   tempFromId === (user.name || '');
          } catch (e) {
            // 解析失败，忽略
          }
        }
      }
      
      // 判断是否是接收的消息
      const tempChatType = (message as any).chat_type || 1;
      let tempIsReceived = false;
      if (tempChatType === 1) {
        // 单聊：to_user_id 是当前用户，且 from_user_id 不是当前用户
        let tempIsToCurrentUser = tempToId === tempCurrentUserId || tempToId === tempCurrentOpenId;
        if (!tempIsToCurrentUser) {
          try {
            const userStr = localStorage.getItem('user') || '{}';
            const user = JSON.parse(userStr);
            tempIsToCurrentUser = tempToId === (user.open_id || '') || 
                                 tempToId === (user.name || '');
          } catch (e) {
            // 解析失败，忽略
          }
        }
        tempIsReceived = tempIsToCurrentUser && !tempIsFromCurrentUser;
      } else {
        // 群聊或其他：from_user_id 不是当前用户
        tempIsReceived = !tempIsFromCurrentUser;
      }
      
      const tempMessageId = `temp_${Date.now()}_${Math.random()}`;
      const processedMessage: Message = {
        message_id: tempMessageId,
        from_user_id: tempFromId,
        to_user_id: tempToId,
        message: String(message.message || ''),
        timestamp_ms: message.timestamp_ms || message.timestamp || Date.now(),
        timestamp: message.timestamp_ms || message.timestamp || Date.now(),
        isReceived: tempIsReceived, // 正确判断是否是接收的消息
        file_url: message.file_url,
        file_name: message.file_name,
        file_type: message.file_type,
        message_content_type: (message as any).message_content_type,
        chat_type: tempChatType,
      };
      messages.value.push(processedMessage);
      await saveMessagesToStorage();
      console.log('✅ 已添加没有 message_id 的消息（使用临时 ID）:', {
        message_id: tempMessageId,
        from_user_id: tempFromId,
        to_user_id: tempToId,
        isReceived: tempIsReceived,
        isFromCurrentUser: tempIsFromCurrentUser,
      });
    }
  }
}

